package com.kaohe.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaohe.domain.PageBean;
import com.kaohe.domain.User;
import com.kaohe.service.LoginService;


/**
 * 登录的表现层
 * 
 * 作用：
 * 		和浏览器相关的操作
 * 
 */
@WebServlet("/loginServlet")
public class LoginServlet extends BaseServlet {
		
	private LoginService service=new LoginService();

	//退出logOut
			public String logOut(HttpServletRequest request, HttpServletResponse response) throws Exception {

				//1.获取session
				HttpSession session = request.getSession();
				
				//2.清除user
				session.invalidate();
				
				//3.重定向到login
				response.sendRedirect(request.getContextPath()+"/admin/login.jsp");	 
				
			return null;

		}
		
	//登录
		public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
	 		 
			
			//处理中文乱码的问题
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
					
			//1.接收参数
			String username = request.getParameter("username");
			String password = request.getParameter("password");

			//2.调用service
			User user=service.login(username,password);
					
			//3.处理结果
					
			String path=null;
			if(user!=null){
						
				//登录成功
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
							
				//重定向到商城管理页面
				response.sendRedirect(request.getContextPath()+"/admin/main.jsp");
						
			}else{
						
				//登录失败
							
				request.setAttribute("msg", "用户名或密码失败");
							
				path= "/admin/login.jsp";
						
			}
			return path;

		}
	//用户管理分页查询findByFen
	public String uquery(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//1.接收参数pageNumber
		String pageNumber = request.getParameter("pageNumber");
		
		//2.设置每页条数
		int pageSize=2;
		
		//3.封装pageBean
		PageBean<User> up =new PageBean<>();
		up.setPageNumber(Integer.parseInt(pageNumber));
		up.setPageSize(pageSize);
		
		//4.service查询
		PageBean<User> cup =service.uquery(up);
		
		//5.request域存储
		request.setAttribute("up", cup);
		
		//6.user_list.jsp  请求转发
		return "/admin/user_list.jsp";
	}
	
	//删除
	public String deUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		//接收cid
		String uid = request.getParameter("uid");
		
		//调用业务层
		service.deUser(uid);
		//重定向
		response.sendRedirect(request.getContextPath()+"/loginServlet?method=uquery&pageNumber=1");
		return null;
		
	}
		 
	
	
}
